/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.prefs.util;

import org.digitalsoul.switchplugin.model.Configuration;

import org.digitalsoul.switchplugin.model.SwitchSet;

import java.io.File;
import java.util.List;


public class SetConfigurator {

    private Configuration config;

    public SetConfigurator(Configuration config) {
        this.config = config;
    }

    public List<SwitchSet> getSets() {
        return config.getSets();
    }

    public Configuration getConfiguration() {
        return config;
    }

    public SwitchSet findSet(String name) {
        SwitchSet foundSet = null;
        for (SwitchSet set : config.getSets()) {
            if (set.getName().equals(name)) {
                foundSet = set;
            }
        }
        return foundSet;
    }
    
    public void removeItem(int index, String name) {
        SwitchSet setToRemove = findSet(name);
        config.getSets().remove(setToRemove);
        if (config.getActiveSet() == setToRemove) {
            if (getSets().size() > 0) {
                if (index > 0) {
                    index--;
                }
                config.setActiveSet(getSets().get(index));
            }
            else {
                config.setActiveSet(null);
            }
        }
    }

    public void setActiveItem(String name) {
        config.setActiveSet(findSet(name));
    }

    public boolean importSet(String filename) {
        SwitchSet set = XMLConverter.importSet(new File(filename));
        boolean importSuccess = set != null;
        if (importSuccess) {
            addSet(set);
        }
        return importSuccess;
    }
    
    public void addSet(SwitchSet set) {
        if (isSetUnique(set)) {
            config.getSets().add(set);
            if (config.getActiveSet() == null) {
                config.setActiveSet(set);
            }
        }
    }
    
    public void addNewSet(String name) {
       addSet(new SwitchSet(name));
    }
    
    private boolean isSetUnique(SwitchSet set) {
        return !hasSet(set.getName());
    }

    public void exportSet(String setName, String fileName) {
        XMLConverter.exportSet(findSet(setName), fileName);
    }

    public boolean hasSet(String name) {
        return findSet(name) != null;
    }

    public boolean isActiveSet(String itemName) {
        SwitchSet activeSet = config.getActiveSet();
        return activeSet != null && activeSet.getName().equals(itemName);
    }
}
